import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  RangePicker,
  Select,
  SelectOption,
  Space,
  Spin,
  Upload
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import * as xlsx from 'xlsx'

import { commonMenuApi } from '@/apis'
import { IndexBlockGoodsItem, IndexBlockItem } from '@/apis/commonMenyTypes'
import { ProTable, ProTableProps, ProTableRef } from '@/components'
import UploadFile from '@/components/UploadFile'
import { useBack, useDialog } from '@/hooks'
import { download, optionsToMap, readFile } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

export default defineComponent({
  name: 'AddOrEditActivity',
  setup() {
    const { handleCancel } = useBack('refreshIndexBlockList')

    const brandTypeOptions = ref([
      { label: '肯德基', value: 1 },
      { label: '麦当劳', value: 2 },
      { label: '星巴克', value: 3 },
      { label: '瑞幸咖啡', value: 4 },
      { label: '话费充值', value: 5 },
      { label: '腾讯视频', value: 6 },
      { label: '爱奇艺', value: 7 },
      { label: '优酷视频', value: 8 },
      { label: '芒果TV', value: 9 },
      { label: '看电影', value: 10 },
      { label: '金豆惠生活', value: 11 },
      { label: '金豆兑好礼', value: 12 }
    ] as OptionItem[])
    const loading = ref(false)
    const route = useRoute()
    const activityData = ref({} as IndexBlockItem)
    const curOptionItem = ref({} as IndexBlockGoodsItem)
    const curOptionItemRef = ref({} as IndexBlockGoodsItem)
    const showDialog = ref(false)
    const dialogLoading = ref(false)
    const submitLoading = ref(false)
    const isAdd = ref(false)
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: false,
      options: {
        border: true,
        align: 'center',
        columns: [
          {
            type: 'seq',
            width: 50,
            title: '序号'
          },
          {
            title: '所属品牌',
            field: 'type',
            width: 100,
            formatter: ({ cellValue }) => {
              return optionsToMap(brandTypeOptions.value)[cellValue]
            }
          },
          {
            title: '商品id',
            field: 'productId',
            width: 150
          },
          {
            title: '商品名称',
            field: 'productName'
          },
          {
            title: '商品图片',
            width: 100,
            slots: {
              default: 'image'
            }
          },
          {
            title: '价格信息',
            width: 200,
            slots: {
              default: 'priceInfo'
            }
          },
          {
            title: '促销样式',
            field: 'promoteLabel',
            width: 100
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ]
      }
    } as ProTableProps)
    onMounted(() => {
      if (route.query.id) {
        getDetail()
      } else {
        activityData.value.status = 1
        activityData.value.goods = []
      }
    })

    //获取详情
    async function getDetail() {
      try {
        loading.value = true
        activityData.value = await commonMenuApi.getIndexBlockDetail(
          route.query.id
        )
        if (activityData.value.startTime) {
          activityData.value.timeRange = [
            moment(activityData.value.startTime),
            moment(activityData.value.endTime)
          ]
        } else {
          activityData.value.timeRange = []
        }
        loading.value = false
      } catch (e) {
        handleCancel()
      }
    }

    //编辑/新增商品
    function editOrAddGoodsItem(rowIndex) {
      isAdd.value = rowIndex == -1
      if (isAdd.value) {
        if (activityData.value.goods.length >= 30) {
          message.error('最多添加30个活动商品')
          return
        }
        curOptionItem.value = { sort: 1 } as IndexBlockGoodsItem
      } else {
        const item = activityData.value.goods[rowIndex]
        item.sort = rowIndex + 1
        Object.assign(curOptionItem.value, item)
        curOptionItemRef.value = item
      }
      showDialog.value = true
    }

    function confirmEditOrAddGoodsItem() {
      if (!curOptionItem.value.productId) {
        message.error('请输入商品id')
        return
      }
      if (!curOptionItem.value.productId) {
        message.error('请输入商品名称')
        return
      }
      if (!curOptionItem.value.img) {
        message.error('请选择商品图片')
        return
      }
      if (!curOptionItem.value.type) {
        message.error('请选择所属品牌')
        return
      }
      if (
        (!curOptionItem.value.saleGold && curOptionItem.value.saleGold !== 0) ||
        (!curOptionItem.value.salePrice && curOptionItem.value.salePrice !== 0)
      ) {
        message.error('请输入售价')
        return
      }
      if (
        !curOptionItem.value.marketPrice &&
        curOptionItem.value.marketPrice !== 0
      ) {
        message.error('请输入划线价')
        return
      }

      let newIndex = curOptionItem.value.sort

      if (isAdd.value) {
        const item = JSON.parse(JSON.stringify(curOptionItem.value))
        if (newIndex > activityData.value.goods.length) {
          activityData.value.goods.push(item)
        } else {
          activityData.value.goods.splice(newIndex - 1, 0, item)
        }
      } else {
        if (newIndex > activityData.value.goods.length) {
          newIndex = activityData.value.goods.length
        }
        const oldIndex = curOptionItemRef.value.sort
        Object.assign(curOptionItemRef.value, curOptionItem.value)
        if (oldIndex != newIndex) {
          const temp = activityData.value.goods[oldIndex - 1]
          activityData.value.goods.splice(oldIndex - 1, 1)
          activityData.value.goods.splice(newIndex - 1, 0, temp)
        }
      }
      tableRef.value.reload()
      showDialog.value = false
    }

    //提交确定
    async function submit() {
      if (!activityData.value.name) {
        message.error('请输入活动名称')
        return
      }
      if (!activityData.value.goods || activityData.value.goods.length == 0) {
        message.error('请添加活动商品')
        return
      }
      if (
        activityData.value.timeRange &&
        activityData.value.timeRange.length > 0
      ) {
        activityData.value.startTime =
          activityData.value.timeRange[0].format('x')
        activityData.value.endTime = activityData.value.timeRange[1].format('x')
      }
      try {
        submitLoading.value = true
        if (activityData.value.id) {
          await commonMenuApi.editIndexBlock(activityData.value)
        } else {
          await commonMenuApi.addIndexBlock(activityData.value)
        }
        handleCancel()
      } finally {
        submitLoading.value = false
      }
    }

    //删除
    function deleteGoodsItem(rowIndex) {
      showConfirm({
        content: '确认删除该商品？',
        onOk: () => {
          activityData.value.goods.splice(rowIndex, 1)
          tableRef.value.reload()
        }
      })
    }

    const { showConfirm } = useDialog()

    return {
      loading,
      activityData,
      submitLoading,
      tableRef,
      tableConfig,
      curOptionItem,
      showDialog,
      dialogLoading,
      brandTypeOptions,
      isAdd,
      handleCancel,
      editOrAddGoodsItem,
      deleteGoodsItem,
      submit,
      confirmEditOrAddGoodsItem
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <h3 style={{ marginLeft: '30px' }}>
            {this.$route.query.id ? '编辑活动' : '新增活动'}
          </h3>
          <Form labelCol={{ span: 2 }}>
            <FormItem label="活动名称" required>
              <Input
                maxlength={60}
                v-model:value={this.activityData.name}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="副标题">
              <Input
                maxlength={60}
                v-model:value={this.activityData.subTitle}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="有效期">
              <RangePicker
                v-model:value={this.activityData.timeRange}
                showTime={{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('23:59:59', 'HH:mm:ss')
                  ]
                }}
                format={'YYYY-MM-DD HH:mm:ss'}
                separator={'至'}
                style={{ width: '400px' }}
              />
            </FormItem>
            <FormItem label="活动商品" required>
              <Button
                type="primary"
                onClick={() => {
                  this.editOrAddGoodsItem(-1)
                }}
              >
                新增
              </Button>
            </FormItem>

            <FormItem
              label=" "
              colon={false}
              v-show={this.activityData.goods?.length > 0}
            >
              <ProTable
                data={this.activityData.goods}
                ref="tableRef"
                style={{ width: '1000px' }}
                v-slots={{
                  image: ({ row }) => <Image src={row.img}></Image>,
                  priceInfo: ({ row }) => {
                    if (row.marketPrice || row.marketPrice == 0) {
                      return (
                        <Space direction="vertical">
                          {'售价：' + handlePrice(row.salePrice, row.saleGold)}
                          {'划线价：￥' + row.marketPrice}
                        </Space>
                      )
                    }
                    return ''
                  },
                  operation: ({ rowIndex }) => (
                    <Space>
                      <Button
                        type="link"
                        size="small"
                        onClick={() => this.deleteGoodsItem(rowIndex)}
                      >
                        删除
                      </Button>
                      <Button
                        type="link"
                        size="small"
                        onClick={() => this.editOrAddGoodsItem(rowIndex)}
                      >
                        编辑
                      </Button>
                    </Space>
                  )
                }}
                {...this.tableConfig}
              />
            </FormItem>
            <FormItem label="状态：" required>
              <RadioGroup v-model:value={this.activityData.status}>
                <Radio value={1}>启用</Radio>
                <Radio value={0}>禁用</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                loading={this.submitLoading}
                onClick={this.submit}
                style={{ marginTop: '30px', marginLeft: '90px' }}
              >
                确定
              </Button>
            </FormItem>
          </Form>
        </Spin>
        <Modal
          v-model:visible={this.showDialog}
          width={500}
          title={this.isAdd ? '新增' : '编辑'}
          destroyOnClose
          onOk={this.confirmEditOrAddGoodsItem}
        >
          <Form labelCol={{ span: 5 }} style={{ marginTop: '15px' }}>
            <FormItem label="所属品牌" required>
              <Select
                v-model:value={this.curOptionItem.type}
                placeholder="请选择"
                style={{ width: '200px' }}
                options={this.brandTypeOptions}
              ></Select>
            </FormItem>
            <FormItem label={'商品id'} required>
              <Input
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.productId}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'商品名称'} required>
              <Input
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.productName}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'商品图片'} required>
              <UploadFile v-model={[this.curOptionItem.img, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'售价'} required>
              <Space>
                {`现金部分`}
                <InputNumber
                  v-model:value={this.curOptionItem.salePrice}
                  placeholder="请输入"
                  maxlength={10}
                  min={0}
                  precision={2}
                  style={{ width: '80px' }}
                />
                {`元 + 金豆部分`}
                <InputNumber
                  v-model:value={this.curOptionItem.saleGold}
                  placeholder="请输入"
                  maxlength={10}
                  min={0}
                  precision={2}
                  style={{ width: '80px' }}
                />
              </Space>
            </FormItem>
            <FormItem label={'划线价'} required>
              <Space>
                <InputNumber
                  v-model:value={this.curOptionItem.marketPrice}
                  placeholder="请输入"
                  min={0}
                  maxlength={10}
                  precision={2}
                  style={{ width: '200px' }}
                />
                {` 元`}
              </Space>
            </FormItem>
            <FormItem label={'排序'} required>
              <InputNumber
                style={{ width: '200px' }}
                v-model:value={this.curOptionItem.sort}
                placeholder="请输入"
                maxlength={3}
                min={1}
              />
            </FormItem>
            <FormItem label={'促销样式'}>
              <Input
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.promoteLabel}
                style={{ width: '200px' }}
                maxlength={8}
                v-slots={{
                  suffix: () => (
                    <span>
                      {this.curOptionItem.promoteLabel?.length || 0}/ 8
                    </span>
                  )
                }}
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
